<template>
    <h1>我是main</h1>
    <button @click="ddddddddd">测试按钮</button>
    <button @click="wwwddd">测试按钮2</button>
    <button @click="talkFun">talkFunBtn</button>
    <br/>
    <button @click="dasdarrwq">测试4</button>
    <button @click="rwqewqeq" class="btnStyle">测试5复制</button>
    <button ref="tipBtnRef">大撒大撒大撒</button>
    <div class="robotTextStyle">
        <span v-html="markdownToHtml(robotTextShow)" id="markdownId"></span>
        <br/><br/>
        <span>{{robotTextShow}}</span>
    </div>
</template>
<script setup>
import { onMounted , ref , watch , getCurrentInstance } from 'vue';
import { getAuthSession , getConversations , postConversations , getConversation , chatRequirements} from '@/api/index'
import Cookies from "js-cookie";
import { v4 as uuidv4 } from 'uuid';
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import Clipboard from 'clipboard'
import tippy from 'tippy.js'
import "tippy.js/dist/tippy.css"
import "tippy.js/animations/scale.css"
const { proxy } = getCurrentInstance()
import { useConversationStore } from '@/store/modules/conversation'
const conversationStore = useConversationStore()
onMounted(()=>{
    // const cookieData = `oai-did=971c0534-2f1e-4507-a0b8-3a5d01fc76f1; intercom-device-id-dgkjq2bp=ea4f2d4f-c311-42fa-a7bc-9a2fec5d65e0; ajs_user_id=user-VimZOTU97xMu1F5gpAu8sZwD; ajs_anonymous_id=anon-cgpt-b9b7553f-deaa-4ecb-a8da-d5f0e37022fc; __Host-next-auth.csrf-token=08005c06786d0d7cdb8c5239444f8b669588bbeae23301a8aa7356c28f467a79%7C752defb6dddcca5e403bc3e61b4d4d6fb46e79a8f9f5ebf4ed045f4eb82842b2; __cf_bm=QbDloBoTwEagtP6mGPhcftiwQjRBVNe5_OjjJDKIBqI-1712109353-1.0.1.1-JQcZZQB7GnayDe7McwnAx3j1VEA0naiYQlql_utR_7I._h1ExOY7NDeyjxAMTaepm30a13zHlsjvLxLYYoICEg; __cflb=0H28vVfF4aAyg2hkHEuhVVUPGkAFmYvk7ptDNGCdJyB; _cfuvid=tMWhvGld0jltqkRfwBn9NTT0ZqnN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3F5ZEFwMmpSZHFzSVBtU1NuTWNTc3I1NjhMWGdoRHA0bXpYTHA5UUw3QWF5eU4yY3VnTWpONGlFdXRBMXlSUVY3eWx6WUtOd2E4R01jbFdjd1dYMnBvMGlXOD0="; _dd_s=rum=0&expire=1712110738640; __Secure-next-auth.callback-url=https%3A%2F%2Fonramp.g1.services.openai.com; __Secure-next-auth.session-token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..GvjgHFNqbcV8UXYm.o4aiHDUTmv0gXc_uQ_M3K2wf0fyjPOjS-k6CvMT3LmKcs6bytyABOnoVkRX0-4Ooc-PwNCm2fKIM6UvS7ylNw3jxlOai_ggAUeh6k4yuRmcXMWjk82NbWUp2jege5sY3E2fp5ySArxLgdnPqFOD5bKRc8fHzA2nqXOByC0eSRnA-Ny_2zIn4TP2ioAyEdrxLFVKz5h6o1nqJ4f08--XwzfOaFj8IsRlXevnUXekvSPB082Nqg7JFDv6JL4oav6Q8t3WHNeIJcRiF5aLPNuUFTFdhYML_7CQm1trO1wmdUFB9Gu9OSQZIVU5yEOmtAdhQ8BR85vOm8ZA4WsX7MuamXGNEy_kec-6elrScYS53VP13dYywqVxsFU52e7fWqZO6Xd-zIoUfpIF3XQRbPMXKnEw0jPvOGeCRCxGw_Eg5afUdLxKFBxscYpJXuew9XR9EOhAFrnDRDAHkupWR8CaJviCy2URRV1EQ54yvzLlqZFPkPttw_8mU04eUIdTFID0Fpc7NhfEF2sPLtwKGZZB_m_HMPbB2CbD-G7te0UusY6LJ5b_vP0a6arpikz4hMr0bZJeKlwOhGQYydJpL79xmEbR51leNYcxBEtISfEsKaaBlz5QhhquGomWAjljrVpJMGQN9NLSa7LI5_5kNJSG6Lc-9hvIpo4mE78sf96xBc3VjV9XCPDLmtjHWNTazalrLEDn6VPp7lPOAwYM-hWTbtWdtZwj5TyGFzFelO3fMTed0BktDO155-qcqr4S_0iDbD63yiFJkpE9a5VLwpsqxNjo4n46Sdy5yjLvOaJnNwKaGLVi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R8hgxPZ-4F1jawqjc8N5FQOcA03YW9tXUIzh5Rc8rHocH4ofCdmVzkjP0k2vJpkiRetObafzw_84tks9Ql6rAwk6YvPZvpHXuarz0eusI-Vy0TF-34UXRQJkCIlFMlfrAJq9769IdytBZwM4ciG3rAEn8cUw4NHMOiN7dAe0vD6xxvNG0Jd4EpA_cYH9W4qXs-jqS1acPLaKO-tkiaWTpUHIr7YcdMXF1KNJYBXveil1OoaXidGwh5O8vB1RIMogcR4ByEV14BQD0mCJ3JhWCf54zoCVXCZ-ZskShZiAh9WDxi-4hV-57eEIdMSEFB8VIAACtB8NNg9VDLsSypULr1yOhGSmGBubPHw0vvHZFEpydjfiFUfk_d1R_s33ohogmrW_lBTkumDVBlG0OPrfn7nOjSNsKKrZUtOg2YYkmaKGJp2PYs4W2wO-8qCABlrGgtsgIcjvbl3EmccFyqW1sydebhwGH8JG3-H43Mv2kiEYdaPYnkBWmym8xEjC3GSQLLnM-D2B9EZCekQ1E1naII8Z3qg-YId2V3WnxdGysBXkQ5EyWBBbM2kXSu6TlpI_9eUG4eGCYbTXkSdlEZSSiMGGMp-AMvZSKph7kftesWv3QgVkVAuYz-ugEn8DVxvrSdXINGXXOglWOBatafaHfRbq-PXG2fOhdVLxHkg2khAKkpc4rTLFykb3KBS2kwNnscZwQw5za6_uYSVAbJpQ45NA1hujsC5c5nuWtsCedzckJXAPp-ylMauy6qwLEjhRK-54xaSKoKJWhzgjVDA_sMDJoFHWs4dLu3eXx3blVl44M_zf9PUtEsH0-ldWz-o2UYdGaNrcC5pSu7v4o2nXIeKFLLvjIc1U8yFiaY6vhmoOwrt1mBobrnGRV0SE2EFR0mCQWmfUAzL5GEkS1KHaTM8gLrnx6Wg-XrHY12eJdXEDb27fDShETl7KBpQjS5f7QvO2lan1Ju0GGHIilCk2IJ7syQHkLCkPeC0Bn3lJ-kQs8n3IG-gjcYCMgrA.xn82LuUgqBGwZkbzIM_hfg`
    // cookieData.split('; ').forEach(item =>{
    //     const [ key , value] = item.split('=')
    //     console.log('key=>',key,'value=>',value);
    //     Cookies.set(key, value)
    // })
    main()
    tippy(proxy.$refs[`tipBtnRef`] ,{
        content: '复制代码',
        animation: 'scale'
    })
    
})
const main = async ()=>{

    // let query = {
    //     offset: 0,
    //     limit: 3,
    //     order: 'updated',
    // }
    // const res = await getConversations(query)

    // const id = 'c1e73be9-a5c7-4b2a-a6d9-ebd2d9200037'
    // const res = await getConversation(id)
    
    
    // const tokenRes = await chatRequirements()
    // conversationStore.setRequirementsToken(tokenRes['token'])

    // const query = {
    //     action: 'next',
    //     messages: [{
    //         id: uuidv4(),
    //         author: {role: 'user'},
    //         content: {
    //             content_type: 'text',
    //             parts: ['你可以使用java写一个helloworld我看看吗！'],
    //     }}],
    //     conversation_id: '39dc5a10-8c15-4b68-8a71-ce42c85ada2f',
    //     parent_message_id: "c0d5cc1a-eb7c-466b-bc5c-b7e2235d91d6",
    //     model: "text-davinci-002-render-sha",
    //     timezone_offset_min: -480,
    //     history_and_training_disabled: false,
    //     conversation_mode: {kind: 'primary_assistant', plugin_ids: null},
    //     force_paragen: false,
    //     force_paragen_model_slug: '',
    //     force_nulligen: false,
    //     force_rate_limit: false,
    //     websocket_request_id: uuidv4(),
    // }
    // const res = await postConversations(query)
    // res.on('data' , val =>{
    //     console.log(val,'#@');
    // })
    // res.on('end' , () =>{
    //     console.log('结束了#@');
    // })
    // console.log(res,'@#');
}
const markdownToHtml = (val) =>{
    const md = new MarkdownIt()
    return md.render(val)
}
const rwqewqeq = ()=>{
    const clipboard = new Clipboard('.btnStyle', {
        text: () => {
            const dom = document.getElementById('markdownId').querySelectorAll('pre code')
            return dom[0].textContent
        }
    })
    clipboard.on('success', (event) => {
        console.log('Text copied!')
        clipboard.destroy()
    })
    clipboard.on('error', (event) => {
        console.error('Failed to copy text')
        clipboard.destroy()
    })
}
const dasdarrwq = ()=>{
}
const wwwddd = async ()=>{
    let query = {
        offset: 0,
        limit: 3,
        order: 'updated',
    }
    const res = await getConversations(query)
}
let setRobotTextShowStatus = ref(false)
const setValue = (i)=>{
    robotTextShow.value = textShowList.value[i]
}
let setTextIndex = ref(0)
const setRobotTextShow = ()=>{
    if(setRobotTextShowStatus.value === false){
        setRobotTextShowStatus.value = true
        const timer =  setInterval(() => {
            if(setTextIndex.value < textShowList.value.length){
                setValue(setTextIndex.value)
                setTextIndex.value++
            }else{
                setRobotTextShowStatus.value = false
                clearInterval(timer)
            }
        }, 20);
    }
    // const timp = new Date()
    // console.log(timp,'@#');
}
import j1 from './stream1.json'
import j2 from './stream2.json'
import j3 from './stream3.json'
import j4 from './stream4.json'
import j5 from './stream5.json'
import j6 from './stream6.json'
import j7 from './stream7.json'
import j8 from './stream8.json'
let list = ref([])
let textShowList = ref([])
let robotTextShow = ref('')
let getRobotTextShowStatus = ref(true)
const ddddddddd = ()=>{
    list.value = []
    textShowList.value = []
    setTextIndex.value = 0
    
    const streamList = [j1,j2,j3,j4,j5,j6,j7,j8]
    let count = 0
    getRobotTextShowStatus.value = false
    const timer = setInterval(async () => {
        if(count < streamList.length){
            dealWithStreamData(streamList[count])
            count++
            setRobotTextShow()
        }else{
            console.log(list.value,'@#');
            getRobotTextShowStatus.value = true
            clearInterval(timer)
        }
    }, 300);
}
watch(() => [ getRobotTextShowStatus.value , setRobotTextShowStatus.value ] , (newVal , oldVal) =>{
    if(newVal[0] === true && newVal[1] === false){
        setMarkDownTextByHighlight()
    }
})
const setMarkDownTextByHighlight = ()=>{
    // const dom = document.getElementById('markdownId').querySelectorAll('pre code')
    // hljs.highlightElement(dom[0]);
    // console.log(dom[0],'@#');
    const preDom = document.getElementById('markdownId').querySelectorAll('pre')
    const codeDom = preDom[0].querySelector('code')
    let languageName = ''
    if(codeDom.classList[0].includes('language-')){
        languageName = codeDom.classList[0].replace('language-','')
    }
    hljs.highlightElement(codeDom);
    preDom[0].insertAdjacentHTML('afterbegin', `<div class="eqwewq">${languageName}   New Div Element</div>`);
    console.log(languageName,'@#');
}
const dealWithStreamData = (val) =>{
    const array = val.split('\n').filter(line => line.trim() !== '' && !line.trim().includes('[DONE]'))
    array.forEach(item =>{
        if(item.includes('data:')){
            item = item.slice(5)
            try {
                const target = JSON.parse(item)
                textShowList.value.push(target['message']['content']['parts'][0])
                list.value.push(target)
            } catch (error) {
            }
        }
    })
}
const talkFun = ()=>{
    return new Promise(async (resolve,reject) =>{
          // 在这里设置你的代理服务器地址
        const proxyUrl = `${window.location.origin}/api`
        const proxyRequestUrl = `${proxyUrl}/backend-api/conversation`;
        const query = {
            action: 'next',
            messages: [{
                id: uuidv4(),
                author: {role: 'user'},
                content: {
                    content_type: 'text',
                    parts: ['你可以使用html写一个helloworld我看看吗?对helloword的字体颜色要标紫'],
            }}],
            conversation_id: '39dc5a10-8c15-4b68-8a71-ce42c85ada2f',
            parent_message_id: "05ac190f-62c9-46d3-93de-502d3f81accd",
            model: "text-davinci-002-render-sha",
            timezone_offset_min: -480,
            history_and_training_disabled: false,
            conversation_mode: {kind: 'primary_assistant', plugin_ids: null},
            force_paragen: false,
            force_paragen_model_slug: '',
            force_nulligen: false,
            force_rate_limit: false,
            websocket_request_id: uuidv4(),
        }
        const tokenRes = await chatRequirements()
        // 发起代理请求
        const options = {
            method: 'post',
            headers: {
                ['Authorization']: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik1UaEVOVUpHTkVNMVFURTRNMEZCTWpkQ05UZzVNRFUxUlRVd1FVSkRNRU13UmtGRVFrRXpSZyJ9.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL3Byb2ZpbGUiOnsiZW1haWwiOiJncHRAamluaGFpLmVtYWlsIiwiZW1haWxfdmVyaWZpZWQiOnRydWV9LCJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsicG9pZCI6Im9yZy13QlRyVzNmU3lxSFBmTklBWWVCdlozeUsiLCJ1c2VyX2lkIjoidXNlci1JcXRFS0thTVJ1OXBwY09LOWNtSWY0RUsifSwiaXNzIjoiaHR0cHM6Ly9hdXRoMC5vcGVuYWkuY29tLyIsInN1YiI6ImF1dGgwfDY1ZmNmYWNmY2MzZjMyNjhkMmVhZWY4MCIsImF1ZCI6WyJodHRwczovL2FwaS5vcGVuYWkuY29tL3YxIiwiaHR0cHM6Ly9vcGVuYWkub3BlbmFpLmF1dGgwYXBwLmNvbS91c2VyaW5mbyJdLCJpYXQiOjE3MTIwMjE2MzksImV4cCI6MTcxMjg4NTYzOSwiYXpwIjoiVGRKSWNiZTE2V29USHROOTVueXl3aDVFNHlPbzZJdEciLCJzY29wZSI6Im9wZW5pZCBwcm9maWxlIGVtYWlsIG1vZGVsLnJlYWQgbW9kZWwucmVxdWVzdCBvcmdhbml6YXRpb24ucmVhZCBvcmdhbml6YXRpb24ud3JpdGUgb2ZmbGluZV9hY2Nlc3MifQ.2IQkbP3g6s7J83NY2E7ONUTvRbi-zoyX5iw94pUaEhSJ2_NVLf_XxnlCzPDm4U4qggO_b43EfYhAQvuzxXIBu0zryvvh9UdzLa2QvDRBnRnmksjsEsCiaj33EFP9l1V0He9XlE7-ujTVNwztcGyzvQj-eS-QAk7BRpIL3JlNMhbMGEFTDlkAar-rmshi8vTVmUUytzOIr4_JBDUNUzAxAu94aId1kr8tiurDqTxDYakV7sL0NLGncJLOvZuqjF8psc3qAgqbVW6rWtMOmOXlj8lsf7hGn3ZfXeFxkLCjkBtGAbp9tPqQEiA3h8oOhOzNGrnSmwGuP254c53SNglHTQ',
                ['Content-Type']: 'application/json;',
                ['accept']: 'text/event-stream;',
                [`openai-sentinel-chat-requirements-token`]: tokenRes['token'],
            },
            body: JSON.stringify(query)
        }
        list.value = []
        textShowList.value = []
        setTextIndex.value = 0
        fetch(proxyRequestUrl, options).then(res=>{
            const reader = res.body.getReader()

            // 逐步读取流中的数据
            const readStream = () => {
                reader.read().then(({ done, value }) => {
                    if (done) {
                        console.log('Stream ended')
                        return;
                    }
                    // 处理数据块，这里假设数据是文本类型
                    const chunk = new TextDecoder().decode(value)
                    dealWithStreamData(chunk)
                    setRobotTextShow()
                    console.log(JSON.stringify(chunk),'#@');
                    // 继续读取下一块数据
                    readStream()
                }).catch(error => {
                    console.error('Error reading stream:', error)
                });
            }

            // 开始读取数据
            readStream();

            console.log(res,'@#');
        }).catch(error=>{
            console.log(error);
        })
    })
}
</script>
<style scoped lang="scss">
.robotTextStyle{
    width: 50vw;
    background-color: rgb(243, 250, 255);
    .eqwewq{
        color: green;
    }
}
:v-deep(.eqwewq){
    color: red !important;
}
</style>